package com.wiloon.java8x.thread.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/*
 * Created by roy on 6/22/17;
 */
public class ThreadStateTest {
    public static void main(String[] args) {
        System.out.println(">");
        new ThreadStateTest().blockedState();
        System.out.println("foo");
    }

    public void blockedState() {
        Runnable runnable = new Runnable() {
            private byte[] lock = new byte[0];

            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
                synchronized (lock) {
                    for (; ; ) {
                        System.out.println(Thread.currentThread().getName() + System.currentTimeMillis());
                        try {
                            TimeUnit.SECONDS.sleep(3);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };

        new Thread(runnable).start();
        new Thread(runnable).start();
    }

    public void runnableThread() {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (; ; ) {
                    System.out.println(Thread.currentThread().getName());
                    System.out.println(Thread.currentThread().getState());
                    try {
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        t.start();

    }

    public void newThread() {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {

            }
        });
        System.out.println(t.getId());
        System.out.println(t.getName());
        System.out.println(t.getPriority());
        System.out.println(t.getState());

        timeWaitTest();
    }

    public void timeWaitTest() {
        synchronized (this) {
            try {
                this.wait(Integer.MAX_VALUE);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void waitTest() {
        synchronized (this) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void sleep() {
        try {
            TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void park() {
        LockSupport.park();
    }

    public static void unParkPark() {

        LockSupport.unpark(Thread.currentThread());
        LockSupport.park();

    }
}
